package com.example.weatherapp1.domain.service



import com.example.weatherapp1.R
import com.example.weatherapp1.data.model.City
import com.example.weatherapp1.data.model.SavedWeather
import com.example.weatherapp1.data.model.WeatherResponse
import com.example.weatherapp1.data.repository.WeatherRepository
import com.google.gson.Gson
import javax.inject.Inject

class WeatherService @Inject constructor(
    private val weatherRepository: WeatherRepository,
    private val gson: Gson
) {
    // 获取并保存天气数据
    suspend fun fetchAndSaveWeather(city: City): WeatherResponse {
        val weatherResponse = weatherRepository.fetchWeather(city.latitude, city.longitude)
        weatherRepository.saveWeather(city.id, weatherResponse)
        return weatherResponse
    }

    // 解析保存的天气JSON数据
    fun parseSavedWeather(savedWeather: SavedWeather): WeatherResponse? {
        return try {
            gson.fromJson(savedWeather.weatherJson, WeatherResponse::class.java)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 获取天气状态对应的资源图标
    fun getWeatherIcon(skyCon: String): Int {
        return when (skyCon) {
            "CLEAR_DAY" -> R.drawable.ic_clear_day
            "CLEAR_NIGHT" -> R.drawable.ic_clear_night
            "PARTLY_CLOUDY_DAY" -> R.drawable.ic_partly_cloudy_day
            "PARTLY_CLOUDY_NIGHT" -> R.drawable.ic_partly_cloudy_night
            "CLOUDY" -> R.drawable.ic_cloudy
            "RAIN" -> R.drawable.ic_rain
            "SNOW" -> R.drawable.ic_snow
            "WIND" -> R.drawable.ic_wind
            "FOG" -> R.drawable.ic_fog
            else -> R.drawable.ic_unknown
        }
    }

    // 获取天气状态的文字描述
    fun getWeatherDescription(skyCon: String): String {
        return when (skyCon) {
            "CLEAR_DAY" -> "晴"
            "CLEAR_NIGHT" -> "晴夜"
            "PARTLY_CLOUDY_DAY" -> "多云"
            "PARTLY_CLOUDY_NIGHT" -> "多云夜"
            "CLOUDY" -> "阴"
            "RAIN" -> "雨"
            "SNOW" -> "雪"
            "WIND" -> "风"
            "FOG" -> "雾"
            else -> "未知"
        }
    }
}
